package com.lkd.handler;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VendoutResultContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.entity.VendoutRunningEntity;
import com.lkd.service.ChannelService;
import com.lkd.service.VendoutRunningService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Topic(TopicConfig.VMS_RESULT_TOPIC)
@Slf4j
public class VendoutResultMsgHandler implements MsgHandler {

    @Autowired
    private VendoutRunningService vendoutRunningService;
    @Autowired
    private ChannelService channelService;

    /**
     * 售货机接收售货机终端返回发货结果的消息
     * @param jsonMsg
     * @throws IOException
     */
    @Override
    public void process(String jsonMsg) throws IOException {
        VendoutResultContract vendoutResultContract = JsonUtil.getByJson(jsonMsg, VendoutResultContract.class);
        //判断是否出货成功
        if (vendoutResultContract.isSuccess()){
            //发货成功，修改流水记录为true
            //根据订单号查找流水记录
            LambdaQueryWrapper<VendoutRunningEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(VendoutRunningEntity::getOrderNo,vendoutResultContract.getVendoutData().getOrderNo());
            VendoutRunningEntity vendoutRunningEntity= vendoutRunningService.getOne(lambdaQueryWrapper);
            vendoutRunningEntity.setStatus(true);
            vendoutRunningService.updateById(vendoutRunningEntity);//更新流水记录

        }else {
            //发货失败,恢复库存
            ChannelEntity channelEntity = channelService.getChannelInfo(vendoutResultContract.getInnerCode(), vendoutResultContract.getVendoutData().getChannelCode());
            channelEntity.setCurrentCapacity(channelEntity.getCurrentCapacity()+1);
            channelService.updateById(channelEntity);//恢复库存


        }


    }
}
